package com.netease.financial.base.share.helper;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.netease.financial.R;
import com.netease.financial.base.share.model.ShareHolder;
import com.netease.financial.common.config.NfsConfig;
import com.netease.financial.common.util.ImageUtil;
import com.netease.financial.common.util.NfsLog;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import im.yixin.sdk.util.BitmapUtil;

/**
 * Created by wyf on 6/28/15.
 */
public class WeChatHelper {

    private static final String TAG = WeChatHelper.class.getSimpleName();

    private final Context mContext;
    private IWXAPI mWxApi;

    private WeChatHelper(Context context) {
        mContext = context;
        mWxApi = WXAPIFactory.createWXAPI(context, NfsConfig.getWeChatAppId());
        mWxApi.registerApp(NfsConfig.getWeChatAppId());

    }

    public static WeChatHelper createHelper(Context context) {
        return new WeChatHelper(context);
    }

    public boolean sendToWeChatFriend(ShareHolder holder) {
        return share(holder, SendMessageToWX.Req.WXSceneSession);
    }

    public boolean shareOnWeChatMoment(ShareHolder holder) {
        return share(holder, SendMessageToWX.Req.WXSceneTimeline);
    }

    private boolean share(ShareHolder holder, int scene) {
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = holder.webUrl;
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = holder.title;
        msg.description = holder.description;
        //这里替换一张自己工程里的图片资源
//        Bitmap thumb = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.mipmap.ic_launcher);
//        msg.setThumbImage(thumb);
        msg.thumbData = BitmapUtil.bmpToByteArray(getThumbnail(holder.imageUrl), true);

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = msg;
        req.scene = scene;
        mWxApi.sendReq(req);
        NfsLog.d(TAG, holder.toString());
        return true;
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    private Bitmap getThumbnail(String imageUrl) {
        Bitmap thumb = ImageUtil.getThumbnail(imageUrl);
        if (thumb == null) {
            thumb = BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_launcher);
        }
        return com.netease.financial.common.util.BitmapUtil.cropCenterBitmap(thumb, 120, 120);
    }
}
